package com.lxw.station.api;

import lombok.SneakyThrows;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.util.List;
import java.util.concurrent.TimeUnit;

public class Selenium {

    public static WebDriver driver;
    public static WebDriverWait wait;

    static {
        // 设置 ChromeDriver 的路径
        System.setProperty("webdriver.chrome.driver", "C:\\118.0.5993.70\\chromedriver-win64\\chromedriver.exe");
        // 配置 ChromeOptions
        ChromeOptions options = new ChromeOptions();
        options.setExperimentalOption("debuggerAddress", "localhost:9222");
        // 创建 ChromeDriver 实例
        driver = new ChromeDriver(options);
        // 隐式等待(全局等待):每隔一段时间循环寻找元素,如果3秒内找到则返回元素,找不到则抛异常
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        // 显示等待器:如果超时就会抛出异常NoTouchElementException
        wait = new WebDriverWait(driver, 5);
        // 添加 shutdown hook
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            if (driver != null) {
                driver.quit();
            }
        }));
    }

    @SneakyThrows
    public static void comment(){
        String content = "文章别有一番风味！让人拍案叫绝，已三连支持，欢迎大佬戳这里回访:https://blog.csdn.net/weixin_41883161/article/details/139407776";
        Thread.sleep(3000);
        driver.navigate().to("https://blog.csdn.net/weixin_43741718/article/details/139441924");
        wait.until(ExpectedConditions.presenceOfElementLocated(By.className("title-article")));
        WebElement commentA = wait.until(ExpectedConditions.presenceOfElementLocated(By.className("go-side-comment")));
        commentA.click();
        Thread.sleep(1000);
        driver.findElements(By.tagName("textarea")).stream().filter(item->"欢迎高质量的评论，低质的评论会被折叠".equals(item.getAttribute("placeholder"))).findFirst().get().sendKeys(content);
        driver.findElements(By.tagName("input")).stream().filter(item->"评论".equals(item.getAttribute("value"))).findFirst().get().click();

    }

    public static void main(String[] args) {
        comment();
    }
}
